package fei.yuzhi.com.loveflowers.fragment.shopping;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.io.File;
import java.io.InputStream;
import java.sql.SQLException;

/**
 * Created by Administrator on 2016/10/20 0020.
 */
public class ShoppingHelper extends OrmLiteSqliteOpenHelper{

    //定义数据库的名称
    private static final String DB_NAME="db_student";
    //定义数据库的版本
    private static final int DB_VERSION=1;
    private static ShoppingHelper helper;
    private Dao<ShoppingBean, Integer> shoppingDao;

    public ShoppingHelper(Context context) {
        super(context, DB_NAME, null,DB_VERSION);
    }

    public ShoppingHelper(Context context, String databaseName, SQLiteDatabase.CursorFactory factory, int databaseVersion, int configFileId) {
        super(context, databaseName, factory, databaseVersion, configFileId);
    }

    public ShoppingHelper(Context context, String databaseName, SQLiteDatabase.CursorFactory factory, int databaseVersion, File configFile) {
        super(context, databaseName, factory, databaseVersion, configFile);
    }

    public ShoppingHelper(Context context, String databaseName, SQLiteDatabase.CursorFactory factory, int databaseVersion, InputStream stream) {
        super(context, databaseName, factory, databaseVersion, stream);
    }
    public static ShoppingHelper getInstamce(Context context){
        if (helper==null){
            helper = new ShoppingHelper(context);

        }
        return helper;
    }


    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource,ShoppingBean.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        if(newVersion>oldVersion){
            //第三个参数表示是否忽略异常
            try {
                TableUtils.dropTable(connectionSource,ShoppingBean.class,true);
                TableUtils.createTable(connectionSource,ShoppingBean.class);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public Dao<ShoppingBean,Integer> getShopping()throws SQLException{
        if (shoppingDao==null){
            shoppingDao = getDao(ShoppingBean.class);
        }
        return shoppingDao;
    }

}
